package FIT::Document::Handler::Product;

use FIT::Class;
use FIT::Util::SpecialChars;
use FIT::Document::Transformer;

extends 'FIT::Document::Handler::Base';

sub handle {
    my ($fixture, $cell, @handlers) = @_;
    $self->expand_row($cell)
        if $cell->detect_mark($MARKER_PRODUCT);
    $self->run_next_handler($fixture, $cell, @handlers);
}

# TODO: complex enough to be a transformer
sub expand_row {
    my $cell         = shift;
    my @list         = $self->eval_expression($cell);
    my $column_index = $cell->column_index;
    my $init_row     = $cell->row;
    my $previous_row = $init_row;
    
    $cell->cut_children;
    transform { Note text is shift @list } $cell;

    for my $item (@list) {
        my $clone_row = $init_row->copy;
        my $clone_cell = [$clone_row->cells]->[$column_index];
        $clone_cell->cut_children;
        transform { Note text is $item } $clone_cell;
        $clone_row->paste(after => $previous_row);
        $previous_row = $clone_row;
    }
}

sub eval_expression {
    my $cell = shift;
    $cell->clear_mark($MARKER_PRODUCT);
    my $code = $cell->fit_text;
    my @list = eval $code;
    die "Error executing list expression [$code]- $@" if $@;
    return @list;
}


=head1 NAME

FIT::Document::Handler::Product - unfold row into one row per list item


=head1 DESCRIPTION

This handler lets you unfold one row into many. It evaluates the code in the
cell, which is expected to return a list. Then it creates a row for each item
in the list. The handled cell value will be the current item from the list.

=cut

